﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HIWSystem.Helpers;
using HIWSystem.Models;
using HIWSystem.Common;
using System.Data;
using System.Windows;
using LiveCharts;
using LiveCharts.Wpf;
using System.Windows.Media;

namespace HIWSystem.ViewModel
{
    public class QCInfoEntryViewModel : ViewModelBase
    {
        #region 属性
        //测试PASS和Fail的数量
        int passCount = 0, failCount = 0;
        //用于判断是不是第一次触发过滤，是则备份原始数据源
        private bool isFirstFilterStation = true;
        //备份原始站位信息
        ObservableCollection<StationsEntity> backupStations = null;

        private ObservableCollection<StationsEntity> stations;
        /// <summary>
        /// 站位信息
        /// </summary>
        public ObservableCollection<StationsEntity> Stations
        {
            get { return stations; }
            set { stations = value; this.RaisePropertyChanged(() => Stations); }
        }
        private StationsEntity selectedStation;
        /// <summary>
        /// 选择的站位实体
        /// </summary>
        public StationsEntity SelectedStation
        {
            get { return selectedStation; }
            set { selectedStation = value; this.RaisePropertyChanged(() => SelectedStation); }
        }
        private string station;
        /// <summary>
        /// 选择的站位
        /// </summary>
        public string Station
        {
            get { return station; }
            set { station = value; this.RaisePropertyChanged(() => Station); }
        }
        private bool isOpenComboStationDropDown;
        /// <summary>
        /// 是否展开站位下拉列表框
        /// </summary>
        public bool IsOpenComboStationDropDown
        {
            get { return isOpenComboStationDropDown; }
            set { isOpenComboStationDropDown = value; this.RaisePropertyChanged(() => IsOpenComboStationDropDown); }
        }
        private string searchStationText;
        /// <summary>
        /// 输入的站位搜索信息
        /// </summary>
        public string SearchStationText
        {
            get { return searchStationText; }
            set { searchStationText = value; this.RaisePropertyChanged(() => SearchStationText); }
        }
        private string sn;
        /// <summary>
        /// 序列号信息
        /// </summary>
        public string SN
        {
            get { return sn; }
            set { sn = value; this.RaisePropertyChanged(() => SN); }
        }
        private string result="PASS";
        /// <summary>
        /// 测试结果
        /// </summary>
        public string Result
        {
            get { return result; }
            set { result = value; this.RaisePropertyChanged(() => Result); }
        }
        private string errorDescription;
        /// <summary>
        /// 异常错误描述
        /// </summary>
        public string ErrorDescription
        {
            get { return errorDescription; }
            set { errorDescription = value; this.RaisePropertyChanged(() => ErrorDescription); }
        }
        private SeriesCollection pieSeriesCollection;
        /// <summary>
        /// 饼形图系列集合
        /// </summary>
        public SeriesCollection PieSeriesCollection
        {
            get { return pieSeriesCollection; }
            set { pieSeriesCollection = value; this.RaisePropertyChanged(() => PieSeriesCollection); }
        }
        private ObservableCollection<TrackingCombineSnEntity> QClogs;
        /// <summary>
        /// QC测试流程
        /// </summary>
        public ObservableCollection<TrackingCombineSnEntity> QCLogs
        {
            get { return QClogs; }
            set { QClogs = value; this.RaisePropertyChanged(() => QCLogs); }
        }
        private ObservableCollection<string> results;
        /// <summary>
        /// 结果
        /// </summary>
        public ObservableCollection<string> Results
        {
            get { return results; }
            set { results = value; this.RaisePropertyChanged(() => Results); }
        }
        #endregion

        #region 命令
        private RelayCommand loadPageCmd;
        /// <summary>
        ///页面加载
        /// </summary>
        public RelayCommand LoadPageCmd
        {
            get 
            {
                if (loadPageCmd==null)
                {
                    loadPageCmd = new RelayCommand(LoadedPage);
                }
                return loadPageCmd; 
            }
            set { loadPageCmd = value; }
        }
        private RelayCommand filterStationCmd;
        /// <summary>
        /// 过滤站位
        /// </summary>
        public RelayCommand FilterStationCmd
        {
            get 
            {
                if (filterStationCmd==null)
                {
                    filterStationCmd = new RelayCommand(FilterStation);
                }
                return filterStationCmd;
            }
            set { filterStationCmd = value; }
        }
        private RelayCommand entryCmd;

        public RelayCommand EntryCmd
        {
            get 
            {
                if (entryCmd==null)
                {
                    entryCmd = new RelayCommand(Entry);
                }
                return entryCmd; 
            }
            set { entryCmd = value; }
        }

        #endregion

        #region 方法
        /// <summary>
        /// 页面加载
        /// </summary>
        private void LoadedPage()
        {
            //初始化测试结果信息
            Results = new ObservableCollection<string>();
            Results.Add("PASS");
            Results.Add("FAIL");
            FillStationToComboBox();
        }
        /// <summary>
        /// 添加站位信息到下拉列表框中
        /// </summary>
        private void FillStationToComboBox()
        {
            int existsCount = 0;//存在的数量
            DataTable dtStations = new DataTable();//系统中质量站位
            Stations = new ObservableCollection<StationsEntity>();
            try
            {
                dtStations = BusinessProcess.GetStations(EnumStationType.QC);
                if (dtStations.Rows.Count>0)
                {
                    for (int i = 0; i < dtStations.Rows.Count; i++)
                    {
                        existsCount = 0;
                        existsCount = Stations.Count(x => x.Station == dtStations.Rows[i]["Station"].ToString());
                        if (existsCount==0)
                        {
                            Stations.Add(new StationsEntity { Station = dtStations.Rows[i]["Station"].ToString() });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 过滤站位
        /// </summary>
        private void FilterStation()
        {
            IsOpenComboStationDropDown = true;
            //当是第一次过滤的时候备份原始数据
            //这样是为了当不输入搜索条件时添加原始数据到列表中
            //当输入搜索条件时生成过滤集合绑定当下拉列表中
            if (isFirstFilterStation)
            {
                backupStations = new ObservableCollection<StationsEntity>();
                backupStations = Stations;
                isFirstFilterStation = false;
            }
            if (!string.IsNullOrEmpty(SearchStationText))
            {
                IEnumerable<StationsEntity> stationEntities = Stations.Where(s => s.Station.ToUpper().Contains(SearchStationText.ToUpper()));
                Stations = new ObservableCollection<StationsEntity>();
                foreach (var s in stationEntities)
                {
                    Stations.Add(s);
                }
            }
            else
            {
                Stations = backupStations;
            }
        }
        /// <summary>
        ///录入信息
        /// </summary>
        private void Entry()
        {
            string startTime = string.Empty;
            string retMsg = string.Empty;//数据库返回的状态码和状态信息
            string[] arrayMsg = new string[2]; //截取返回的状态码和状态信息
            TrackingEntity trackingEntity = new TrackingEntity();
            DataTable dtTracking = new DataTable();
            if (string.IsNullOrEmpty(this.Station))
            {
                MessageBox.Show("站位信息不能为空!", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (!ValidSn())
                return;
            if (string.IsNullOrEmpty(this.Result))
            {
                MessageBox.Show("结果信息不能为空!", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (this.Result == "FAIL")
            {
                if (string.IsNullOrEmpty(this.ErrorDescription))
                {
                    MessageBox.Show("错误描述信息不能为空!", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
            }
            startTime = DateTime.Now.ToString();
            trackingEntity.Sn = this.SN.ToUpper();
            trackingEntity.Station = this.Station.ToUpper();
            trackingEntity.Result = this.Result.ToUpper();
            trackingEntity.EquipmentName = Environment.MachineName;
            trackingEntity.StartTime = startTime;
            trackingEntity.StopTime = DateTime.Now.ToString();
            trackingEntity.Actor = LogInInfo.User;
            //retMsg = "OK|插入成功!"; --用于调试使用
            retMsg = BusinessProcess.AddEndTracking(trackingEntity, out dtTracking);
            arrayMsg = retMsg.Split('|');
            if (arrayMsg[0] == "OK")
            {
                //首次添加要初始化Log集合
                if (QCLogs == null)
                    QCLogs = new ObservableCollection<TrackingCombineSnEntity>();

                QCLogs.Add(new TrackingCombineSnEntity
                {
                    Sn = this.SN.ToUpper() ?? "",
                    PN = BusinessProcess.GetPNBySn(this.SN),
                    Station = this.Station.ToUpper() ?? "",
                    FailDescription = this.ErrorDescription ?? "",
                    Result = trackingEntity.Result,
                    Actor = LogInInfo.User,
                    CreateAt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                });
                //根据时间进行降序排序，便于将最近一条记录显示再最上面。
                var a = QCLogs.OrderByDescending(x => Convert.ToDateTime(x.CreateAt)).ToList();
                QCLogs = new ObservableCollection<TrackingCombineSnEntity>();
                for (int i = 0; i < a.Count; i++)
                {
                    QCLogs.Add(new TrackingCombineSnEntity
                    {
                        Sn = a[i].Sn ?? "",
                        PN = a[i].PN ?? "",
                        Station = a[i].Station ?? "",
                        Result = a[i].Result ?? "",
                        FailDescription = a[i].FailDescription ?? "",
                        FailValue = a[i].FailValue ?? "",
                        Actor = a[i].Actor ?? "",
                        CreateAt = a[i].CreateAt ?? ""
                    });
                }
                this.SN = "";
                this.ErrorDescription = "";
                this.Result = "PASS";
                if (trackingEntity.Result == "PASS")
                {
                    passCount += 1;
                }
                else
                {
                    failCount += 1;
                }
                this.AddPieSeriesData();//刷新饼形图
            }
            else
            {
                MessageBox.Show(arrayMsg[1], "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }
        /// <summary>
        /// 验证序列号信息
        /// </summary>
        /// <returns></returns>
        private bool ValidSn()
        {
            try
            {
                if (string.IsNullOrEmpty(this.SN))
                {
                    MessageBox.Show("序列号信息不能为空,请输入序列号信息.", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }
                if (!BusinessProcess.SNIsExists(this.SN))
                {
                    MessageBox.Show("序列号【" + this.SN + "】在系统中不存在,请重新输入.", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 添加图标数据
        /// </summary>
        void AddPieSeriesData()
        {
            List<string> titles = new List<string> { "PASS", "FAIL" };
            ChartValues<double> chartvalue = new ChartValues<double>();
            PieSeriesCollection = new SeriesCollection();
            for (int i = 0; i < titles.Count; i++)
            {
                chartvalue = new ChartValues<double>();
                PieSeries series = new PieSeries();
                if (titles[i] == "PASS")
                {
                    chartvalue.Add(passCount);
                    series.Fill = Brushes.Green;
                }
                else
                {
                    chartvalue.Add(failCount);
                    series.Fill = Brushes.Red;
                }
                series.DataLabels = true;
                series.Title = titles[i];
                series.Values = chartvalue;
                PieSeriesCollection.Add(series);
            }
        }
        #endregion
    }
}
